<template>
  <div class="login">
    <!-- 用户名 -->
     <el-form :rules='rules' ref="form" :model="form" label-width="80px">
        <el-form-item label="用户名:" prop='username'>
          <el-input clearable placehoder="请输入账号" v-model="form.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item label="密  码:" prop='password'>
          <el-input show-password type="password" placehoder="请输入密码" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="login-btn" type="primary" @click='login'>登录</el-button>
          <el-button type="info" @click='reset'>重置</el-button>
        </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data () {
    return {
      form: {
        username: '',
        password: ''
      },
      // 表单校验规则对象
      rules: {
        // 校验用户名
        username: [
          // trigger,可以同时校验几个事件
          { required: true, message: '账号不能为空', trigger: ['blur', 'change'] },
          { pattern: /^1\d{4,10}$/, message: '账号必须是5-11位的数字', trigger: ['blur', 'change'] }
        ],
        // 校验密码
        password: [
          // trigger,可以同时校验几个事件
          { required: true, message: '密码不能为空', trigger: ['blur', 'change'] },
          { pattern: /^\w{3,12}$/, message: '密码必须是3-12为的字符', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    // 重置
    reset () {
      // 获取到表单组件
      this.$refs.form.resetFields()
    },
    // 登录校验
    async login () {
      try {
        await this.$refs.form.validate()
        const res = await this.$axios.post('/login', this.form)
        const { statusCode, data } = res.data
        if (statusCode === 200) {
          // this.$message({
          //   type: 'success',
          //   message: '登录成功',
          //   direction: 2000
          // })
          // 添加提示
          this.$message.success('登录成功')
          // 登录成功,把token保存到本地
          localStorage.setItem('token', data.token)
          localStorage.setItem('user', JSON.stringify(data.user))
          // 登陆成功,跳转到首页
          this.$router.push('/')
        } else {
          this.$message({
            type: 'error',
            message: '用户名或者密码错误',
            direction: 2000
          })
        }
      } catch (e) {
        this.$message.error('校验失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-form {
  width: 330px;
  margin: 0 auto;
  margin-top: 230px;
  border: 1px solid #daa520;
  background-color: #daa520;
  border-radius: 15px;
  padding-top: 40px;
  padding-right: 40px;

  .login-btn {
    margin-right: 80px;
  }
}

</style>
